package me.fenglu.base.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

public class GuiceUtil {

	private static List<Module> modules;
	private static final String MODULE_PACKAGE = "";

	static {
		modules = new ArrayList<Module>();
		String path = GuiceUtil.class.getResource("/").getPath();
		path += MODULE_PACKAGE.replace(".", "/");
		File root = new File(path);
		traversingPackage(root, modules);
	}

	public static Injector createInjector() {
		Injector injector = Guice.createInjector(modules);
		return injector;
	}

	public static <T> T newInstance(Class<T> cls) {
		return (T) GuiceUtil.createInjector().getInstance(cls);
	}

	private static void traversingPackage(File root, List<Module> modules) {
		File[] files = root.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				traversingPackage(file, modules);
			} else if (file.isFile()) {
				String fileName = file.getName();
				if (fileName.contains(".")) {
					String extension = fileName.substring(fileName.lastIndexOf("."));
					if (extension.equals(".class")) {
						String rootDir = root.getName();
						String className = "";
						if (MODULE_PACKAGE.substring(MODULE_PACKAGE.lastIndexOf(".")).contains(rootDir)) {
							className = MODULE_PACKAGE + "." + fileName.substring(0, fileName.lastIndexOf("."));
						} else {
							className = MODULE_PACKAGE + "." + rootDir + "."
									+ fileName.substring(0, fileName.lastIndexOf("."));
						}
						try {
							Class<?>[] interfaces = Class.forName(className).getSuperclass().getInterfaces();
							if (interfaces.length != 0) {
								for (Class<?> i : interfaces) {
									if (i.getName().equals("com.google.inject.Module")) {
										modules.add((Module) Class.forName(className).newInstance());
										break;
									}
								}
							}
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						} catch (InstantiationException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	public static void main(String[] args) {
	}
}
